﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Vra.Components.Models.Menu;
using Vra.Components.ViewModels.Menu;
using MenuItem = Vra.Components.Models.Menu.MenuItem;

namespace Vra.Components.Menu
{
	/// <summary>
	/// Компонент отображает меню
	/// </summary>
	public partial class MenuControl : UserControl
	{
		public static readonly DependencyProperty MenuProperty =
			DependencyProperty.Register(
				"Menu",
				typeof(MenuList),
				typeof(MenuControl),
				new FrameworkPropertyMetadata(MenuPropertyChangedCallback));

		public static readonly DependencyProperty SelectedProperty =
			DependencyProperty.Register("Selected", typeof (MenuItem), typeof (MenuControl), new PropertyMetadata(default(MenuItem)));

		public MenuItem Selected
		{
			get { return (MenuItem) GetValue(SelectedProperty); }
			set { SetValue(SelectedProperty, value); }
		}

		public MenuList Menu
		{
			get { return (MenuList)GetValue(MenuProperty); }
			set { SetValue(MenuProperty, value); }
		}

		public MenuControl()
		{
			InitializeComponent();
			ViewModel = new MenuViewModel();
			ViewModel.PropertyChanged += ViewModelOnPropertyChanged;
		}

		private void ViewModelOnPropertyChanged(object sender, PropertyChangedEventArgs args)
		{
			if (args.PropertyName != "SelectedItem" || !(sender is MenuViewModel))
				return;
			Selected = (sender as MenuViewModel).SelectedItem;
		}

		private MenuViewModel ViewModel
		{
			get { return Root.DataContext as MenuViewModel; }
			set { Root.DataContext = value; }
		}

		private static void MenuPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var @this = d as MenuControl;
			if (@this == null)
				return;
			var newVal = e.NewValue as MenuList;
			@this.ViewModel.Menu = newVal;
		}
	}
}
